//音乐播放js，挺老的代码了，当时是用原生js编写，注释很全。挪到这里面我用JQuery修改了很多方法并添加了一些逻辑和缓存，就有下面原生js和JQuery混用的情况。
//默认播放列表，不是我喜欢这首歌，这仅仅是一个默认随便选的歌曲
let music_list = [

    {
            "id": "-1",
            "name": "飞驰于天空的废铁浪漫",
            "singer": "东方远空界",
            "duration": "04:56",
            "src": "hoppin/static/audio/dfykj.mp3",
            "type":"default"
    },{
          "id": "-2",
          "name": "时间刺客艾克",
          "singer": "英雄联盟",
          "duration": "03:05",
          "src": "hoppin/static/audio/ekko.mp3",
          "type":"default"
      },{
          "id": "-3",
          "name": "烈日的暴君",
          "singer": "东方邪星章",
          "duration": "05:57",
          "src": "hoppin/static/audio/lrbj.mp3",
          "type":"default"
      },
]
//formateTime(61)--->01:01

//获取各种标签
let player = document.querySelector("#player");
let bz_music = document.querySelector("#bz_music");

//歌曲信息部分
let left_photo = document.querySelector("#left_photo");
let list_title = document.querySelector("#list_title");
let list_singer = document.querySelector("#list_singer");
let process_slide = document.querySelector("#process_slide");
let process = document.querySelector("#process");
let showHide = document.querySelector("#showHide");

//控制按钮部分
let time = document.querySelector("#time");
let btnPlay = document.querySelector("#btnPlay");
let volume_slide = document.querySelector("#volume_slide");
let volume = document.querySelector("#volume");

//播放列表部分
let play_list = document.querySelector("#play_list");
let play_list_area = document.querySelector("#play_list_area");


let music_heart=document.querySelector(".music-heart");
//播放列表初始是关闭的
play_list_area.style.display = "none";

//喜欢音乐
function likeMusic(){
    let song=music_list[play_index];
    if(song.type=="default"){
        alert("默认歌曲不允许操作")
    }else{
        //验证音乐是否被喜欢,喜欢的取消喜欢,未喜欢的喜欢
        //document.querySelector('div').getAttribute('data-user-id');
        if(music_heart.getAttribute('data-store')=="1"){
            //移除indexDB关于歌曲的内容
            localforage.removeItem("zq__music:"+song.id).then(function() {
                alert("取消喜欢成功");
                music_heart.setAttribute()
                $(".music-heart").css("color","#fff1e5").data("store","0");
            }).catch(function(err) {
                alert("取消喜欢失败");
            });
        }else{
            //添加喜欢的歌曲详情
            localforage.setItem("zq__music:"+song.id, song);
            $(".music-heart").css("color","#ad1313").data("store","1");
            alert("喜欢成功");
        }
    }
}
//动态加载播放列表
function loadPlayList(list) {
    $("#play_list").html("");
    //遍历播放列表
    for (let i = 0; i < list.length; i++) {
        //将每个对象，分别存到music中
        let music = list[i];
        //创建li标签
        let liTag = document.createElement("li");
        let divtag=document.createElement("div");
        //创建歌曲名span标签
        let spanTitleTag = document.createElement("p");
        //创建时长span标签
        let spanDurationTag = document.createElement("span");

        //为ul添加li标签，子节点
        play_list.appendChild(liTag);
        liTag.appendChild(divtag);
        //为li标签，添加子节点
        divtag.appendChild(spanTitleTag);
        divtag.appendChild(spanDurationTag);

        //添加内容
        spanTitleTag.innerHTML = music.name;
        spanDurationTag.innerHTML = music.duration;

        //添加类名
        spanTitleTag.classList.add("list_title");
        spanDurationTag.classList.add("list_time");

        //自定义属性
        //需要用的时候，直接从标签中取值，不需要和后台交互
        liTag.setAttribute("data-index", i);
        liTag.setAttribute("data-type", music.type);
        //当点击每一个li标签的时候
        //重新载入歌曲信息(专辑图片、歌曲路径、歌曲名、歌手名)
        //播放当前点击的音乐
        liTag.addEventListener("click", function () {
            //获取每个li标签的歌曲id
            let index = this.getAttribute("data-index");
            //将歌曲id赋给，全局变量play_index
            play_index = index;
            //调用载入歌曲函数
            loadMusic();
            //播放音乐
            playMusic();

            $(this).addClass("active_music_list").siblings().removeClass("active_music_list");
        })
    }
}

//载入歌曲信息
function loadMusic() {
    let music = music_list[play_index];
    //改变专辑图片
    //left_photo.src = music.images;
    //改变歌曲名
    list_title.innerHTML = music.name;
    //改变歌手名
    list_singer.innerHTML = music.singer;
    //改变歌曲路径
    player.src = music.src;
    localforage.getItem("zq__music:"+music.id, function(err, value) {
        if (value != null) {
            $(".music-heart").css("color","#ad1313").data("store","1");
        }else{
            $(".music-heart").css("color","#fff1e5").data("store","0");
        }
    });
}

//播放,暂停音乐
btnPlay.addEventListener("click", function () {
    //paused,表示当前音乐是否为暂停状态
    if (player.paused) {
        //play(),播放当前音乐
        playMusic();
    } else {
        //pause(),暂停当前音乐
        player.pause();
        btnPlay.setAttribute("class", "btn_play fa fa-play");
    }
})

//上一曲
function backword() {
    if (play_index == 0) {
        play_index = music_list.length - 1;
    } else {
        //改变播放序号
        play_index--;
    }
    //重新载入
    loadMusic();
    //播放
    playMusic();
    $("#play_list").find("li").each(function (index,element) {
        if($(element).data("index")==play_index){
            $(element).addClass("active_music_list").siblings().removeClass("active_music_list");
            return;
        }
    })
}

//音乐结束自动下一首
player.addEventListener('ended', function () {
    forward();
}, false);

//下一曲
function forward() {
    if (play_index == music_list.length - 1) {
        play_index = 0;
    } else {
        //改变播放序号
        play_index++;
    }
    //重新载入
    loadMusic();
    //播放
    playMusic();
    $("#play_list").find("li").each(function (index,element) {
        if($(element).data("index")==play_index){
            $(element).addClass("active_music_list").siblings().removeClass("active_music_list");
            return;
        }
    })
}

//播放
function playMusic() {
    player.play();
    btnPlay.setAttribute("class", "btn_play fa fa-pause");
}


//时间转换
function formateTime(time) {
    if (time > 3600) {
        let hour = parseInt(time / 3600);
        let minute = parseInt(time % 3600 / 60);
        let second = parseInt(time % 3600);
        hour = hour >= 10 ? hour : "0" + hour;
        minute = minute >= 10 ? minute : "0" + minute;
        second = second >= 10 ? second : "0" + second;
        return hour + ":" + minute + ":" + second;
    } else {
        let minute = parseInt(time / 60);
        let second = parseInt(time % 60);
        minute = minute >= 10 ? minute : "0" + minute;
        second = second >= 10 ? second : "0" + second;
        return minute + ":" + second;
    }
}

//设置定时器
window.setInterval(function () {
    //currentTime,当前播放的秒数
    time.innerHTML = formateTime(player.currentTime);
    //duration,当前音乐的总时长,秒数
    let percent = player.currentTime / player.duration;
    process_slide.style.width = percent * 100 + "%";
}, 100)

//静音
function volumeOff() {
    //volume,[0,1]
    player.volume = 0;
    window.localStorage.setItem("zq__main_web:volume:music",0);
    volume_slide.style.width = 0;
}

//最大音 
function volumeUp() {
    player.volume = 1;
    window.localStorage.setItem("zq__main_web:volume:music",1);
    volume_slide.style.width = "100%";
}

//通过滑块控制音量大小
volume.addEventListener("click", function (event) {
    //得到当前点击的位置
    let currentVolume = event.offsetX / this.offsetWidth;
    //设置音量
    player.volume = currentVolume;
    window.localStorage.setItem("zq__main_web:volume:music",currentVolume);
    volume_slide.style.width = currentVolume * 100 + "%";
})

//通过滑块控制音乐进度
process.addEventListener("click", function (event) {
    //计算点击位置的百分比
    let currentValue = event.offsetX / this.offsetWidth;
    //因为我们已经设置了定时器,在实时监控我们当前音乐的变化
    //因此,我们通过设置当前播放的音乐时长,影响我们的进度条
    player.currentTime = player.duration * currentValue;
})

//显示隐藏播放列表
function showMusicList() {
    //当前已经显示播放列表
    if (flag) {
        play_list_area.style.display = "none";
        bz_music.style.width = "300px";
        showHide.style.color = "#666";
        flag = 0;
    } else {
        play_list_area.style.display = "block";
        bz_music.style.width = "500px";
        showHide.style.color = "#DDD";
        flag = 1;
    }
}


//播放序号
let play_index = 0;
//初始音量
player.volume = 0.5;
//初始化显示播放列表
//当flag为1的时候,表示列表显示(当前状态)
//当flag为0的时候,表示列表隐藏(当前状态)
let flag = 0;

//初始化
firstInit();

function timeduration(duration) {
    let st = parseInt(duration / 1000);
    let m = parseInt(st / 60);
    let s = st % 60;
    return "" + addZero(m) + ":" + addZero(s);
}

function addZero(num){
    if (parseInt(num) < 10) {
        num = '0' + num;
    }
    return num;
}

//初始化
function firstInit() {
    let firstSong = music_list[0];
    $("#player").attr("src", firstSong.src);
    $("#list_title").text(firstSong.name);
    $("#list_singer").text(firstSong.singer);

    let search_song_name=window.localStorage.getItem("zq__main_web:search:music:name");
    $(".search_music_input").val(search_song_name);
    let volume=window.localStorage.getItem("zq__main_web:volume:music");
    if(volume==null){
        volume=player.volume;
    }else{
        player.volume=volume
    }

    volume_slide.style.width =  volume * 100 + "%";
    //迭代喜欢的歌曲
    localforage.iterate(function(value, key, iterationNumber) {
        if(key.indexOf("zq__music")!=-1){
            music_list.push(value)
        }
    }).then(function() {
        loadPlayList(music_list);
    }).catch(function(err) {
        loadPlayList(music_list);
    });

    //回车搜索
    $(".search_music_input").keydown(function (e) {
        if (e.keyCode == 13) {
            $(".search_music").click();
            e.preventDefault();
        }
    })
}

//搜索歌曲
$(".search_music").click(function () {
    let search_song_name = $(".search_music_input").val();
    if (!search_song_name.trim().length){
        search_song_name = "爱的供养";
        $(".search_music_input").val(search_song_name)
    }else{
        window.localStorage.setItem("zq__main_web:search:music:name",search_song_name);
    }

    $.ajax({
        url: 'http://1.15.232.156:3000/search?keywords=' + search_song_name,
        success: function (data) {
            let songs = data.result.songs;
            music_list=[];
            $.each(songs, function (index, value) {
                let artist = "";
                $.each(value.artists, function (index, value) {
                    artist += value.name + " ";
                })
                music_list.push({
                    id: value.id,
                    name: value.name,
                    singer: artist,
                    type:"search",
                    duration: timeduration(value.duration),
                    src: "http://music.163.com/song/media/outer/url?id=" + value.id +
                        ".mp3",
                })
            });
            loadPlayList(music_list);
            flag=0;
            showMusicList();
        }
    })

})
